package pierwszy;

import java.text.Format.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.internal.PropertyUtils;

import static org.assertj.core.api.Assertions.*;



@Test
public class LogInTest{
	static WebDriver driver;
    static WebDriverWait wait;
    
    private String PortalLink = "http://www.bermar2.home.pl/ks_portal/login.php";
    private String login = "p.jaworek";
    private String password = "jawso98*";
    
    @BeforeClass
    void setUp() {
    	System.out.println("Przed klasą");
        driver = new FirefoxDriver();
        wait = new WebDriverWait(driver,30);
        driver.manage().window().maximize();
        //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }
    
    @AfterClass
    static void tearDown() {
    	System.out.println("Za klasą");
    	//driver.quit();
        //driver.close();
    }
    
    @BeforeMethod
    void setUpTest(){
    	System.out.println("Przed metodą testową");
    	driver.get(PortalLink);
    }
    
    @AfterMethod
    void tearDownTest(){
    	System.out.println("Za metodą testowa");
    }
    
    
    @DataProvider(name="PlusOptions")
    public Object[][] createDataForPlusOption(){
    	return new Object[][]{
    			{"Aktualność ", 					"Aktualności"},
    			{" Klienta  ", 						"Firmy"},
    			{" Pracownika / Administratora  ", 	"Pracownicy"},
    			{"Zlecenie zwykłe ", 				"Zlecenia"},
    			{"Zobowiązanie wobec US ", 			"Płatności"},
    			{" Składkę zus ", 					"Płatności"},
    			{" Notkę  ", 						"Notki"}
    	};
    }
    
    @DataProvider (name="siteNames")
    public Object[][] createDataForChooseSite(){
    	return new Object[][]{
    			{"ks_portal", "ks_portal"},
    			{"ks_dotacje", "ks_dotacje"},
    			{"ks_ksiegowosc", "ks_ksiegowosc"}
    	};
    }
    
    
    @Parameters({ "login", "password" })
    @Test (groups = "groupA", threadPoolSize = 1, invocationCount = 10,  timeOut = 10000)
	public void LogInLogOut(String lgn, String paswd){
		System.out.println("LogInTest");

		//driver.get(PortalLink);
		LogInPage Login = new LogInPage(driver, wait);  
		
		MainPage MP = Login.logIn(lgn,paswd);	
		
		Login = MP.LogOut();
	}
    
	@Test (groups = "groupA")
	public void AddRemoveNote() throws InterruptedException {
		String noteCategory = "Publiczna"; //prywatna, publiczna
		String[] noteFilterCategory = {"Prywatna", "Publiczna", "Wszystkie"};
		String noteContent = "Notka 1 WP " + Utils.getCurrentDate();
		String site = "ks_portal";
		System.out.println("AddRemoveNote");
		List<WebElement> allNotesList = new ArrayList<WebElement>();
		StringBuffer sB = new StringBuffer();
		
		//Login
		LogInPage Login = new LogInPage(driver, wait);  
		MainPage MP = Login.logIn(login,password);	
		
		KsPortalPage KSP = MP.chooseSite(site);
		
		//Check if KsPortal was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.SelectedSite));
		assert driver.findElement(UiMapping.SelectedSite).getText().equals(site);
		
		KSP.getOptionFromIconPlus(" Notkę  ");
		
		KSP.addNote(noteCategory, noteContent);
		
		for (String category : noteFilterCategory){
			KSP.chooseNoteCategory(category);
		
			wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.notesContent));
			allNotesList = driver.findElements(UiMapping.notesContent);
			
		//	System.out.println("teeeksks: " + driver.findElement(By.xpath("//tbody/tr/td/span[text()='»']/following-sibling::a/text()")));
			
			for (WebElement we : allNotesList){
				sB.append(we.getText());					
			}
			
			//Check if note was added.
			if(category.equals(noteCategory) || category.equals("Wszystkie")){
//				wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.passNoteContentCheck(noteContent)));
//				assert driver.findElement(UiMapping.passNoteContentCheck(noteContent)).getText().equals(noteContent);
				
				assertThat(sB).contains(noteContent);
			}
			else {		
				assertThat(sB).doesNotContain(noteContent);			
			}
		}
		
		KSP.removeNote(noteContent);	
		
		Login = KSP.LogOutKsPortalPage();
	}
	
	@Test (groups = "groupA")
	public void AddRemoveNews() throws InterruptedException{
		String title = "Title1WP";
		String shortage = "Shortage1WP";
		String text = "Text1\nWP\nTest";
		String site = "ks_portal";
		int newsCountAdd = 0;
		int newsCountRemove = 0;
		
		System.out.println("AddRemoveNews");

		//LogIn
		LogInPage Login = new LogInPage(driver, wait); 
		MainPage MP = Login.logIn(login,password);
		
		//Choose and Check KsPortal site	
		KsPortalPage KSP = MP.chooseSite(site);
		
		//Check if KsPortal was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.SelectedSite));
		assert driver.findElement(UiMapping.SelectedSite).getText().equals(site);
		
		KSP.getOptionFromIconPlus("Aktualność ");
		
		List <WebElement> DateTimeOfAddedNewsWebElements = KSP.fillInNews(title, shortage, text);
		
		List <String> DateTimeOfAddedNewsString = KSP.getDateTimeOfNews(DateTimeOfAddedNewsWebElements);
		
		KSP.submitNews();

		newsCountAdd = KSP.getNewsCount();
		
		WebElement foundNews = KSP.findNewsByTitleAndDate(title, DateTimeOfAddedNewsString);
		
		//Check title, date and time of addition
		if(foundNews != null){
			//Check title of added news.
			KSP.removeNews();
			
			newsCountRemove = KSP.getNewsCount();
			assert newsCountAdd - newsCountRemove == 1 : "Ilość aktualności jest nieporpawna";
			
			System.out.println("Aktualność została usunięta");
		}
		else{
			assert false : "Aktualność nie została odnaleziona";
		}
		
//		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.passNewsTitle(title, DateTimeOfAddedNewsString.get(0))));
//		WebElement news = driver.findElement(UiMapping.passNewsTitle(title, DateTimeOfAddedNewsString.get(0)));
//		
//		System.out.println("tytuł" + title);
//		assert news.getText().equals(title):"There is no news with following title: " + title ;
//		news.click();
//		
//		//Check text of added news.
//		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.NewsTextTab));
//		WebElement newsTextTab = driver.findElement(UiMapping.NewsTextTab);
//		newsTextTab.click();
//
//		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.NewsTextAreaCheck));
//		WebElement newsText = driver.findElement(UiMapping.NewsTextAreaCheck);
//		assert newsText.getText().equals(text): "There is no news with following text: " + text;
	
		Login = KSP.LogOutKsPortalPage();
	}
	
	@Test (groups = "groupB")
	public void AddCheckAndRemoveUser(){
		WebElement foundEmployee;
		String site = "ks_portal";
		String iconPlusOption = " Pracownika / Administratora  ";
		String iconPlusOptionCheck = "Pracownicy";
		String[] userData = {"User1WPTest", "12345678", "12345678", "Adam", "Kowalski", "100", "Księgowa", "Drawsko Pomorskie", "78-500", "Mickiewicza 5/42",
				             "123-555-323", "www.user@wp.pl", "www.user.pl", "User\ntest\ndodatkowe informacje"};
		String employeeOption = "Usuń";
		
		System.out.println("AddCheckAndRemoveEmployee");

		//LogIn
		LogInPage Login = new LogInPage(driver, wait); 
		MainPage MP = Login.logIn(login,password);
		
		//Choose and Check KsPortal site	
		KsPortalPage KSP = MP.chooseSite(site);
		
		//Check if KsPortal was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.SelectedSite));
		assert driver.findElement(UiMapping.SelectedSite).getText().equals(site) : "Site " + site + " was not chosen.";
		
		//Choose and Check IconPlusOption (Employee)	
		KSP.getOptionFromIconPlus(iconPlusOption);
		
		//Check if Employee option was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.IconPlusCheck));
		assert driver.findElement(UiMapping.IconPlusCheck).getText().equals(iconPlusOptionCheck) : "Option " + iconPlusOption + " was not chosen.";
		
		//Set user data
		KSP.setNewUser(userData);
		
		//Clean user data
		KSP.cleanUserInfo();
		
		//Check if data was cleaned
		assert KSP.checkIfCleaned(userData) : "User data was not cleaned.";
		
		//Set user data
		KSP.setNewUser(userData);
		
		//Add new user
		KSP.addNewUser();
		
		foundEmployee = KSP.findEmployeeByLoginAndName(userData[0], userData[3], userData[4]);
		
		assert foundEmployee!=null: "Employee was not found!";
		
		//Find and remove Employee
		KSP.employeeChooseOption(userData[0], userData[3], userData[4], employeeOption);
		
	}
	
	@Test
	public void AddEmployeeLocation(){
		//Test variables
		LogInPage Login;
		KsPortalPage KSP;
		MainPage MP;
		WebElement lastLocation;
		String locationText = "";
		String locationAdres = "";
		
		//Test data
		String site = "ks_portal";
		String iconPlusOption = " Pracownika / Administratora  ";
		String iconPlusOptionCheck = "Pracownicy";
		Map<String,String> locationFiledNamesValuesMap = new TreeMap<String,String>();
		locationFiledNamesValuesMap.put("Nazwa:", "Lokalizacja Drawsko Pomorskie");
		locationFiledNamesValuesMap.put("Ulica:", "Złocieniecka");
		locationFiledNamesValuesMap.put("Numer lokalu:", "C");
		locationFiledNamesValuesMap.put("Numer budynku:", "4d");
		locationFiledNamesValuesMap.put("Miasto:", "Drawsko Pomorskie");
		locationFiledNamesValuesMap.put("Kod pocztowy:", "90-510");
		locationFiledNamesValuesMap.put("Poczta:", "Drawsko Pomorskie");
		locationFiledNamesValuesMap.put("Ilość miejsc:", "12");
		locationFiledNamesValuesMap.put("Opis:", "testowy opis lokalizaji");
		locationFiledNamesValuesMap.put("Wyposażenie:", "komputer, internet");
		locationFiledNamesValuesMap.put("Podlega rezerwacji:", "tak");
		
		//LogIn
		Login = new LogInPage(driver, wait); 
		MP = Login.logIn(login,password);
				
		//Choose and Check KsPortal site	
		KSP = MP.chooseSite(site);
				
		//Check if KsPortal was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.SelectedSite));
		assert driver.findElement(UiMapping.SelectedSite).getText().equals(site) : "Site " + site + " was not chosen.";
				
		//Choose and Check IconPlusOption (Employee)	
		KSP.getOptionFromIconPlus(iconPlusOption);
		
		//Check if Employee option was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.IconPlusCheck));
		assert driver.findElement(UiMapping.IconPlusCheck).getText().equals(iconPlusOptionCheck) : "Option " + iconPlusOption + " was not chosen.";
	
		//add new Location
		assert KSP.setNewEmployeeLocation(locationFiledNamesValuesMap) : "Field names are incorrect.";
		
		lastLocation = KSP.findLastLocation();
		
		KSP.openLocation(lastLocation);
		
		locationText = KSP.getLocationContent();
		
		//assert content of newly added location
		locationAdres = "Adres:\nUlica: " + locationFiledNamesValuesMap.get("Ulica:") + " " + 
				locationFiledNamesValuesMap.get("Numer budynku:") + " / " + locationFiledNamesValuesMap.get("Numer lokalu:") + '\n' + locationFiledNamesValuesMap.get("Miasto:");
		
		assertThat(locationText).
			startsWith(locationFiledNamesValuesMap.get("Nazwa:")).
			endsWith(locationFiledNamesValuesMap.get("Kod pocztowy:") + " " + locationFiledNamesValuesMap.get("Poczta:")).
			containsOnlyOnce("Ilość miejsc: " + locationFiledNamesValuesMap.get("Ilość miejsc:")).
			containsOnlyOnce("Podlega rezerwacji.").
			containsOnlyOnce(locationAdres);
	
		String locationDescription = KSP.getLocationDescription();
		
		assertThat(locationDescription).isEqualTo(locationFiledNamesValuesMap.get("Opis:"));
	}
	
	@Test (groups = "groupB")
	public void addCheckAndRemoveClient(){
		String clientType ="osoba fizyczna" ;//available client types ("firma", "osoba fizyczna") 
		
		String site = "ks_portal";
		String iconPlusOption = " Klienta  ";
		String iconPlusOptionCheck = "Firmy"; 
		String AmountOfCompaniesAfter;
		String AmountOfCompaniesBefore;

		Map<String,String> clientTypeMap = new TreeMap<String,String>();
		clientTypeMap.put("osoba fizyczna", "Klienci (dodaj klienta - osoba fizyczna)");
		clientTypeMap.put("firma", "Firmy (dodaj firmę)");
		
		Map<String,String> clientTypeEmailLoginMap = new TreeMap<String,String>();
		clientTypeEmailLoginMap.put("osoba fizyczna", "Client1WPTest");
		clientTypeEmailLoginMap.put("firma", "jst.m.jaworskii9@bermar.pl");//jst.m.jaworski@bermar.pl
		
		String[] naturalPersonData = {"Client1WPTest", "12345678", "12345678", "Adam", "Kowalski"};
		String[][] companyData = {/*"Client1WPTest",*/ 
				{"12345678", "12345678", "Firma Testowa WPTest1234567", "WPTest"},
				{},
				{},
				{},
				{},
				{}
		};
		
		System.out.println("addCheckAndRemoveClient");

		
		//LogIn
		LogInPage Login = new LogInPage(driver, wait); 
		MainPage MP = Login.logIn(login,password);
		
		//Choose and Check KsPortal site	
		KsPortalPage KSP = MP.chooseSite(site);
		
		//Check if KsPortal was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.SelectedSite));
		assert driver.findElement(UiMapping.SelectedSite).getText().equals(site) : "Site " + site + " was not chosen.";
		
		//Choose and Check IconPlusOption (Employee)	
		KSP.getOptionFromIconPlus(iconPlusOption);
		
		//Check if Employee option was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.IconPlusCheck));
		assert driver.findElement(UiMapping.IconPlusCheck).getText().equals(iconPlusOptionCheck) : "Option " + iconPlusOption + " was not chosen.";
		
		//choose client type
		assert KSP.chooseClientType(clientType) : "Unavailable cient type!";
		
		//Check if mentioned client type was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.checkSelectedClientType));
		assert driver.findElement(UiMapping.checkSelectedClientType).getText().equals(clientTypeMap.get(clientType)) : "Client '" + clientType + "' was not chosen.";
		
		//check if following login, email is available.
		Boolean emailLoginAvailibility = KSP.checkClienEmailLogin(clientType, clientTypeEmailLoginMap.get(clientType));
		
		if(emailLoginAvailibility){
			if(clientType.equals("osoba fizyczna")){
				KSP.setClientData(clientType, naturalPersonData);
				KSP.addNewNaturalPersonClient();
				AmountOfCompaniesBefore = KSP.getAmountOfElements();
				
				WebElement FoundedNaturalPerson = KSP.findNaturalPersonByNameAndLogin(naturalPersonData);
				if(FoundedNaturalPerson != null){
					KSP.removeNaturalPersonByNameAndLogin(naturalPersonData);
					AmountOfCompaniesAfter = KSP.getAmountOfElements();
					
					if(Integer.parseInt(AmountOfCompaniesBefore) - Integer.parseInt(AmountOfCompaniesAfter) != 1){
						assert false : "NaturalPerson: " + naturalPersonData[0] + " was not removed";
					}
				}
			}
			else if (clientType.equals("firma")){
				KSP.setCompanyClientData(companyData);
				
				KSP.addNewCompanyClient();
				
				AmountOfCompaniesBefore = KSP.getAmountOfElements();
				
				WebElement FoundedCompany = KSP.findCompanyByName(companyData);
				
				if(FoundedCompany != null){

					FoundedCompany.click();
					KSP.removeFoundedComapny();
					AmountOfCompaniesAfter = KSP.getAmountOfElements();
	
					if(Integer.parseInt(AmountOfCompaniesBefore) - Integer.parseInt(AmountOfCompaniesAfter) != 1){
						assert false : "Company: " + companyData[0][2] + " was not removed";
					}
				}
				else{
					assert false : "Company: " + companyData[0][2] + " was not found.";
				}
			}
		}
		
	}
	
	
	@Test(groups = "groupB", dataProvider="PlusOptions")
	public void checkAllIconPlusOptions(String IconPlusOption, String IconPlusOptionCheck){
		String site = "ks_portal";

		//LogIn
		LogInPage Login = new LogInPage(driver, wait); 
		MainPage MP = Login.logIn(login,password);
				
		//Choose and Check KsPortal site	
		KsPortalPage KSP = MP.chooseSite(site);
				
		//Check if KsPortal was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.SelectedSite));
		assert driver.findElement(UiMapping.SelectedSite).getText().equals(site) : "Site " + site + " was not chosen.";

		//Choose and Check IconPlusOption (Employee)	
		KSP.getOptionFromIconPlus(IconPlusOption);
				
		//Check if Employee option was chosen.
		wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.IconPlusCheck));
		assert driver.findElement(UiMapping.IconPlusCheck).getText().equals(IconPlusOptionCheck) : "Option " + IconPlusOption + " was not chosen.";
		
	}
	
	
	@Test (dataProvider = "siteNames")
	public void checkAllSites(String site, String checkSite){
		//LogIn
				LogInPage Login = new LogInPage(driver, wait); 
				MainPage MP = Login.logIn(login,password);
						
				//Choose and Check KsPortal site	
				KsPortalPage KSP = MP.chooseSite(site);
				
				//Check if KsPortal was chosen.
				wait.until(ExpectedConditions.presenceOfElementLocated(UiMapping.passSelectedSite(site)));
				assert driver.findElement(UiMapping.passSelectedSite(site)).getText().trim().equals(checkSite) : "Site " + checkSite + " was not chosen.";
				
				KSP.LogOutKsPortalPage();
	}
	
	
	//NEW APPROACH - FULL PAGE OBJECT
	
	@Test
	public void checkAllKsSites() throws InterruptedException{
		//Open and login Portal
		LogInPage Login = new LogInPage(driver, wait);
		MainPage MP = Login.logIn(login, password);
		
		//Select and check Ks Ksiegowosc
		MP.selectKsKsiegowosc();
		assertThat(MP.getStateOfKsKsiegowoscRBtn()).isTrue();
		
		//Select and check Ks Dotacje
		MP.selectKsDotacje();
		assertThat(MP.getStateOfKsDotacjeRBtn()).isTrue();
		
		//Select and check Ks Portal
		MP.selectKsPortal();
		assertThat(MP.getStateOfKsPortalRBtn()).isTrue();
		
//		KsKPage KSK = MP.submitKsKsiegowosc();
//		KSK.selectIconPlus();
//		KSK.closeIconPlus();
//		KSK.LogOut();
//		Login.logIn(login, password);
		
		String noteType = "Prywatna";
		String noteText = "notka testowa WP";
		
		KsPPage KSP = MP.submitKsPortal();
		KSP.selectIconPlus();
		KSP.closeIconPlus();
		KSP.typeNip("123456789");
		NotePage NP = KSP.submitNote();
		
		
		NotesListPage NLP = NP.chooseListNotesOption();
		NLP.chooseAddNoteOption();

		NP.addNewNote(noteType, noteText);
		NoteContentPage NCP = NLP.openLastNote();
		
		assertThat(NCP.getNoteType().getText()).isEqualTo(noteType);
		assertThat(NCP.getNoteText().getText()).isEqualTo(noteText);
		
		NCP.chooseListNotesOption();
		
		//NCP.goBackToNotesList();
		
		NLP.deleteLastNoteDismiss();
		
		NLP.deleteLastNoteAccept();
		
		NCP.chooseAddNoteOption();
		
		KsDPage KSD = NLP.chooseKsDotacje();
		Thread.sleep(3000);
		KsDModulesPage KSDM = KSD.selectKsDModules();
		KSDM.closeModulesPage();
		
		
		KsKPage KSK = KSD.chooseKsKsiegowosc();
		Thread.sleep(3000);
		KsKModulesPage KSKM = KSK.selectKsKModules();
		KSKM.closeModulesPage();
		
		KSK.chooseKsPortal();
		Thread.sleep(3000);
		KsPModulesPage KSPM = KSP.selectKsPModules();
		KSPM.closeModulesPage();
		
		
		KSP.LogOut();
		Login.logIn(login, password);
		
//		KsDPage KSD1 = MP.submitKsDotacje();
//		KSD1.selectIconPlus();
//		KSD1.closeIconPlus();
//		KSD1.LogOut();
//		Login.logIn(login, password);
	}
	
}

